import uuid

from sqlalchemy.orm import Session
from . import models, schemas
from fastapi import HTTPException
from .cache import save_token


def get_users(db: Session):
    return db.query(models.User).all()


def get_user(db: Session, username: str):
    return db.query(models.User).filter(models.User.username == username).first()


def get_user_by_id(db: Session, id: int):
    return db.query(models.User).filter(models.User.id == id).first()


def read_user(name: str, pwd: str, db: Session):
    user = get_user(db, username=name)
    if not user or user.auth_string != pwd:
        return {"msg": "User or Password is wrong!"}
    if not user.is_active:
        return {'msg': '当前用户未激活，请先激活账户', 'url': f'/active/{user.id}'}
    token: str = uuid.uuid4().hex
    save_token(user_id=user.id, token=token)
    return {"user": user, "token": token}


def remove_user_by_id(db: Session, id: int):
    db.query(models.User).filter(models.User.id == id).delete()
    db.commit()
    return True


def update_user(db: Session, user_id: int, update_item: schemas.UserInfo):
    db.query(models.User).filter(models.User.id == user_id).update(update_item)
    db.commit()
    return db.query(models.User).filter(models.User.id == user_id).first()


def update_user_avater(db: Session, user_id: int, avater_filename: str):
    db.query(models.User).filter(models.User.id == user_id).update({"profile_picture": avater_filename})
    db.commit()
    return db.query(models.User).filter(models.User.id == user_id).first()


def create_user(db: Session, user: schemas.RegistUser):
    db_user = models.User(
        username=user.username,
        auth_string=user.password,
        nick_name=user.nick_name,
        email=user.email,
        mobile=user.mobile
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    # db_user.__dict__.update({"token":"token value"})  # 如果需要添加额外字段
    return db_user


def active_user(db: Session, id: int):
    user = db.query(models.User).filter(models.User.id == id).first()
    if not user:
        raise HTTPException(status_code=404, detail="账户不存在")
    if user.is_active:
        raise HTTPException(status_code=403, detail="账户已激活")
    db.query(models.User).filter(models.User.id == id).update({"is_active": 1})
    db.commit()
    return db.query(models.User).filter(models.User.id == id).first()
